package com.lagouedu.kucun.miaosha.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lagouedu.kucun.miaosha.service.MService;
import com.lagouedu.kucun.miaosha.util.Constants;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MServiceImpl implements MService {

    Logger logger = LoggerFactory.getLogger(MServiceImpl.class);

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DefaultMQProducer producer;

    @Override
    public Integer getRemainNum() {
        Object o = redisTemplate.opsForValue().get(Constants.LAGOU_PHONE_REMAIN);
        Integer aaa = (Integer)redisTemplate.opsForValue().get("aaa");
        return Integer.valueOf(String.valueOf(o));
    }

    @Override
    public Boolean sendMessage() {
        return null;
    }

    public RLock getLock(String lockKey){
        RLock lock = redissonClient.getLock(lockKey);
        return lock;
    }

    @Override
    public void reduceRemainNum() {
        redisTemplate.opsForValue().decrement(Constants.LAGOU_PHONE_REMAIN);
    }

    public void increRemainNum(){
        redisTemplate.opsForValue().increment(Constants.LAGOU_PHONE_REMAIN);
    }

    @Override
    public void doMiaosha(String userId) {
        // 扣减redis库存
        reduceRemainNum();
        // 发送消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userId", userId);
        jsonObject.put("productId", 1);
        Message message = new Message("topic_miaosha_lagouphone",jsonObject.toJSONString().getBytes());
        try {
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    //
                    logger.info("发送消息成功！user_id{}",userId);
                }

                @Override
                public void onException(Throwable throwable) {
                    // 回滚redis库存
                    increRemainNum();
                    logger.error("发送消息失败，回滚redis库存 ----{}",redisTemplate.opsForValue().get(Constants.LAGOU_PHONE_REMAIN));
                }
            });
        } catch (MQClientException e) {
            increRemainNum();
            e.printStackTrace();
        } catch (RemotingException e) {
            increRemainNum();
            e.printStackTrace();
        } catch (InterruptedException e) {
            increRemainNum();
            e.printStackTrace();
        }
    }
}
